<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="500" align-center>
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      class="form-wrap"
      label-width="120px"
    >
      <el-form-item label="关键词" prop="keyword">
        <ns-input v-model="formData.keyword" placeholder="请输入关键词" />
      </el-form-item>
      <el-form-item label="上级关键词组" prop="parentId">
        <el-cascader
          style="width: 100%"
          v-model.trim="formData.parentId"
          :options="ketWordTree"
          :props="cascaderProps"
          clearable
          placeholder="请选择上级关键词组"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="关键词组" prop="keywordType">
        <el-input
          style="width: 100%"
          v-model.trim="formData.keywordType"
          clearable
          placeholder="请输入关键词组"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="结构化类型：" prop="type">
        <el-select v-model="formData.type" clearable placeholder="请选择标准类型">
          <el-option label="非结构化数据" value="0" />
          <el-option label="结构化数据" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { createKeyword, updateKeyword, getKeyword } from '@/api/develop/featureLibrary/keyword'
import { getKeywordTree } from '@/api/develop/featureLibrary/keyword'

export type FormType = 'create' | 'update' | ''
interface RestaurantItem {
  value: string
}

const props = defineProps<{ types: string[] }>()

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const dialogTitle = ref('') // 弹窗的标题
const ketWordTree = ref([])

const formType = ref<FormType>('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  id: undefined,
  keyword: '',
  keywordType: '',
  parentId: '',
  type: ''
})

const cascaderProps = ref({
  checkStrictly: true,
  label: 'keywordType',
  value: 'id',
  children: 'children',
  emitPath: false
})

const getKeyWordTree = async () => {
  const data = await getKeywordTree()
  ketWordTree.value = data || []
}

const formRules = reactive({
  keyword: [{ required: true, message: '关键词不能为空', trigger: ['blur', 'change'] }],
  keywordType: [{ required: true, message: '关键词组不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '结构化类型不能为空', trigger: 'change' }]
})
const formRef = ref<FormInstance>() // 表单 Ref

const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value

  cb(results)
}
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

const handleSelect = (item: RestaurantItem) => {
  console.log(item)
}

const restaurants = computed<RestaurantItem[]>(() => {
  return props.types.map((item) => ({
    value: item
  }))
})

/** 打开弹窗 */
const open = async (type: FormType, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getKeyWordTree()
  if (id) {
    formLoading.value = true
    try {
      const res = await getKeyword(id)
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value?.validate()

  // 提交请求
  formLoading.value = true
  try {
    const data = toRaw(formData.value)
    data.parentId = data.parentId ? data.parentId : '0'

    if (formType.value === 'create') {
      await createKeyword(data)
      message.success(t('common.createSuccess'))
    } else {
      await updateKeyword(data)
      message.success(t('common.updateSuccess'))
    }
    closeDialog()
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/** 重置表单 */
const resetForm = () => {
  formLoading.value = false

  formData.value = {
    id: undefined,
    keyword: '',
    keywordType: ''
  }
  formRef.value?.resetFields()
}

function closeDialog() {
  dialogVisible.value = false
}

watch(dialogVisible, (show) => {
  !show && resetForm()
})
</script>
<style lang="scss" scoped>
// .form-wrap {
//   height: 120px;
//   display: flex;
//   flex-direction: column;
//   justify-content: center;
//   :deep(.el-form-item) {
//     margin-bottom: 0;
//   }
// }
</style>
